const express = require('express');
const router = express.Router();
const pool = require('./db');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const iconv = require('iconv-lite');

// 确保上传目录存在
const uploadDir = 'uploads';
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
}

// 自定义存储引擎，保留原始文件名并进行转码
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        const originalName = file.originalname;
        const decodedName = iconv.decode(Buffer.from(originalName, 'latin1'), 'utf8');
        const filePath = path.join(uploadDir, decodedName);

        fs.access(filePath, fs.constants.F_OK, (err) => {
            if (!err) {
                return cb(new Error('文件已存在，禁止上传'), null);
            }
            cb(null, decodedName);
        });
    }
});

const upload = multer({ storage: storage });

// 上传资源接口（修改后）
router.post('/upload-resource', upload.single('resourceFile'), async (req, res) => {
    // 添加基本的登录检查
    if (!req.session.user_id) {
        return res.status(401).json({ message: '用户未登录' });
    }

    const { courseCode, permission, attachment, belongChapter, resourceId } = req.body;
    const { user_id } = req.session;
    const resourcePath = req.file? req.file.path : null;

    if (!resourcePath) {
        return res.status(400).json({ message: '文件上传失败，可能是文件已存在' });
    }

    try {
        await pool.execute('INSERT INTO resources (resource_id, resource_content, course_code, uploader_user_id, permission, attachment, belong_chapter) VALUES (?,?,?,?,?,?,?)', 
            [resourceId, resourcePath, courseCode, user_id, permission, attachment, belongChapter]);
        res.json({ message: '资源上传成功' });
    } catch (error) {
        console.error('Error uploading resource:', error);
        res.status(500).json({ message: '服务器错误', error: error.message });
    }
});

// 获取课程资源接口
router.get('/get-resources/:courseCode', async (req, res) => {
    const { courseCode } = req.params;
    try {
        const [rows] = await pool.execute('SELECT * FROM resources WHERE course_code =?', [courseCode]);
        res.json(rows);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 下载资源接口
router.get('/download-resource/:resourceId', async (req, res) => {
    const resourceId = req.params.resourceId;
    try {
        const [rows] = await pool.execute('SELECT resource_content FROM resources WHERE resource_id =?', [resourceId]);
        if (rows.length > 0) {
            const resourcePath = rows[0].resource_content;
            const fileName = path.basename(resourcePath);
            res.download(resourcePath, fileName, (err) => {
                if (err) {
                    console.error('Error downloading resource:', err);
                    res.status(500).json({ message: '下载资源失败' });
                }
            });
        } else {
            res.status(404).json({ message: '资源未找到' });
        }
    } catch (error) {
        console.error('Error downloading resource:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取资源对应的课程代码
router.get('/get-resource-course-code/:resourceId', async (req, res) => {
    const resourceId = req.params.resourceId;
    try {
        const [rows] = await pool.execute('SELECT course_code FROM resources WHERE resource_id =?', [resourceId]);
        if (rows.length > 0) {
            res.json({ courseCode: rows[0].course_code });
        } else {
            res.status(404).json({ message: '资源未找到' });
        }
    } catch (error) {
        console.error('Error getting resource course code:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 资源所有版本
router.get('/get-resource-versions/:resourceId', async (req, res) => {
    const resourceId = req.params.resourceId;
    try {
        const [rows] = await pool.execute('SELECT * FROM resources WHERE resource_id = ? OR attachment = ? ORDER BY create_time DESC', [resourceId, resourceId]);
        res.json(rows);
    } catch (error) {
        console.error('Error getting resource versions:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 资源详细信息
router.get('/get-resource-info/:resourceId', async (req, res) => {
    const resourceId = req.params.resourceId;
    try {
        const [rows] = await pool.execute('SELECT * FROM resources WHERE resource_id =?', [resourceId]);
        if (rows.length > 0) {
            res.json(rows[0]);
        } else {
            res.status(404).json({ message: '资源未找到' });
        }
    } catch (error) {
        console.error('Error getting resource info:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 预览资源接口
router.get('/preview-resource/:resourceId', async (req, res) => {
    const resourceId = req.params.resourceId;
    try {
        const [rows] = await pool.execute('SELECT resource_content FROM resources WHERE resource_id =?', [resourceId]);
        if (rows.length > 0) {
            const resourcePath = rows[0].resource_content;
            const resourceName = path.basename(resourcePath);
            const fileExtension = path.extname(resourcePath).toLowerCase().substring(1);

            const supportedTypes = {
                'pdf': 'application/pdf',
                'mp3': 'audio/mpeg'
            };

            if (supportedTypes[fileExtension]) {
                res.setHeader('Content-Type', supportedTypes[fileExtension]);
                res.setHeader('Content-Disposition', `inline; filename="${encodeURIComponent(resourceName)}"`);
                res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
                res.setHeader('Pragma', 'no-cache');
                res.setHeader('Expires', '0');

                const fileStream = fs.createReadStream(resourcePath);
                fileStream.on('error', (err) => {
                    console.error('Error reading file:', err);
                    res.status(500).json({ message: '文件读取错误' });
                });
                fileStream.pipe(res);
            } else {
                res.status(400).json({ message: '该文件类型不支持在线预览' });
            }
        } else {
            res.status(404).json({ message: '资源未找到' });
        }
    } catch (error) {
        console.error('Error previewing resource:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 检查 resource_id 是否已存在的接口
router.get('/check-resource-code', async (req, res) => {
    const { resourceId } = req.query;
    try {
        const [rows] = await pool.execute('SELECT * FROM resources WHERE resource_id =?', [resourceId]);
        res.json({ exists: rows.length > 0 });
    } catch (error) {
        console.error('Error checking resource code:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 学习资源记录接口
router.post('/learn-resource', async (req, res) => {
    const { resource_id, user_id } = req.body;
    
    if (!resource_id || !user_id) {
        return res.status(400).json({ message: '缺少必要参数' });
    }
    
    try {
        const [existingRows] = await pool.execute(
            'SELECT * FROM learned_resource WHERE resource_id =? AND user_id =?', 
            [resource_id, user_id]
        );
        
        if (existingRows.length === 0) {
            await pool.execute(
                'INSERT INTO learned_resource (resource_id, user_id) VALUES (?, ?)', 
                [resource_id, user_id]
            );
            res.json({ message: '学习记录已创建', action: 'inserted' });
        } else {
            res.json({ message: '学习记录已存在', action: 'existed' });
        }
    } catch (error) {
        console.error('Error learning resource:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取用户已学资源的id
router.get('/get-learned-resources', async (req, res) => {
    const userId = req.query.userId;
    try {
        const [rows] = await pool.execute('SELECT resource_id FROM learned_resource WHERE user_id =?', [userId]);
        const resourceIds = rows.map(row => row.resource_id);
        res.json(resourceIds);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 标记资源为未学
router.post('/mark-as-unlearned', async (req, res) => {
    const { resource_id, user_id } = req.body;
    if (!resource_id || !user_id) {
        return res.status(400).json({ message: '缺少必要参数' });
    }
    try {
        await pool.execute(
            'DELETE FROM learned_resource WHERE resource_id =? AND user_id =?', 
            [resource_id, user_id]
        );
        res.status(200).json({ message: '标记资源为未学成功' });
    } catch (error) {
        console.error('Error learning resource:', error);
        res.status(500).json({ message: '服务器错误' });
    }
});

module.exports = router;